/*
 * Copyright (c) 2013, marco.tamburelli@gmail.com
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met: 
 * 
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer. 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution. 
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.omorphdb.core.storage;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.omorphdb.core.io.Constants;
import org.omorphdb.core.storage.document.Document;
import org.omorphdb.core.storage.document.DocumentDescriptor;
import org.omorphdb.core.storage.document.Field;
import org.omorphdb.core.storage.document.FieldFactory;
import org.omorphdb.core.value.Value;

final class DocumentImpl implements Document
{
	private final DocumentDescriptorImpl descr;
	private final FieldFactory factory;

	private final Map<String, Field<?>> attrMap;

	DocumentImpl(DocumentDescriptorImpl descr, FieldFactory factory)
	{
		this.attrMap = new TreeMap<>();

		this.descr = descr;
		this.factory = factory;
	}

	@Override
	public DocumentDescriptor getDescriptor()
	{
		return this.descr;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> Value<T> get(String field)
	{
		if (this.attrMap.containsKey(field)) return (Value<T>) this.attrMap.get(field).getValue();
		else return null;
	}

	@Override
	public <T> void set(String field, Value<T> value) throws IOException
	{
		update(field, value);
	}

	@SuppressWarnings("unchecked")
	<T> void setNoUpdate(String field, Value<T> value) throws IOException
	{
		Field<T> f;

		if (this.attrMap.containsKey(field)) f = (Field<T>) this.attrMap.get(value.get());
		else
		{
			f = this.factory.createField(this.descr, field, value.getType());
			this.attrMap.put(field, f);
		}

		f.setValue(value, false);
	}

	private <T> void update(String field, Value<T> value) throws IOException
	{
		this.descr.updated = true;

		if (this.descr.docSize >= 0)
		{
			@SuppressWarnings("unchecked")
			Field<T> attribute = (Field<T>) this.attrMap.get(field);

			if (attribute == null)
			{
				attribute = this.factory.createField(this.descr, field, value.getType());
				attribute.setValue(value, true);
				this.attrMap.put(field, attribute);
			}
			else
			{
				Value<?> tmpValue = attribute.getValue();
				attribute.setValue(value, true);

				this.descr.docSize -= tmpValue.size();

				/* In the size also the field name is relevant */
				this.descr.docSize -= Constants.SIZEOF_INT;
				this.descr.docSize -= field.getBytes().length;
				this.descr.attributesCount--;
			}

			if (value != null)
			{
				this.descr.docSize += value.size();

				/* In the size also the field name is relevant */
				this.descr.docSize += Constants.SIZEOF_INT;
				this.descr.docSize += field.getBytes().length;
				this.descr.attributesCount++;
			}
		}
	}

	/**
	 * Creates an empty new document.
	 * 
	 * @param classID A string containing class information (string with java
	 *        class canonical form).
	 * @param factory
	 * @return
	 */
	public static Document createDocument(int classID, FieldFactory factory)
	{
		DocumentDescriptorImpl descr = DocumentDescriptorImpl.defineNew(classID);
		return descr.createDocument(factory);
	}

	Collection<Field<?>> fields()
	{
		return this.attrMap.values();
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof Document)
		{
			Document obj2 = (Document) obj;

			DocumentDescriptor descriptor = obj2.getDescriptor();
			if (descriptor.getClassID() != this.descr.classID) return false;

			int attributesCount = descriptor.getAttributesCount();
			if (attributesCount != this.descr.attributesCount) return false;

			for (Entry<String, Field<?>> e : this.attrMap.entrySet())
			{
				Value<?> expected = e.getValue().getValue();
				Value<Object> compare = obj2.get(e.getKey());
				if (!expected.equals(compare)) return false;
			}

			return true;
		}

		return false;
	}
}
